package com.xopencode.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

/**
 * TCP服务-服务器端
 * @Author mcb
 * @Version 1.0
 */
public class NettyServer {
    public static void main(String[] args) throws InterruptedException {
        //1、创建两个线程组 bossGroup workGroup
        //bossGroup线程组负责客户端连接
        EventLoopGroup bossGroup=new NioEventLoopGroup();
        //workGroup线程组负责网络读写操作
        EventLoopGroup workGroup=new NioEventLoopGroup();
        //2、创建服务器启动助手来配置参数--创建辅助的工具类，用于服务器通道的一些列配置
        ServerBootstrap serverBootstrap=new ServerBootstrap();
        //链式编程
        serverBootstrap.group(bossGroup,workGroup)//绑定两个线程组
        .channel(NioServerSocketChannel.class)//指定NIO模式
        .option(ChannelOption.SO_BACKLOG,512)//设置TCP缓冲区
        .childOption(ChannelOption.SO_KEEPALIVE,true)//保持连接
        .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {//数据接收方法的处理
                ch.pipeline().addLast(new StringDecoder()); //数据由字节转字符串，ByteBuf
                ch.pipeline().addLast(new NettyServerHandler());//具体业务的处理
            }
        });
        System.out.println("Server : 准备就绪！！！");
        //3 绑定端口,设置非堵塞
        ChannelFuture cf = serverBootstrap.bind(8765).sync();
        ChannelFuture cf2 = serverBootstrap.bind(8766).sync();//--绑定多个端口，开口变大，但是处理能力不变
        System.out.println("Server : 启动！！！");
        //4 关闭通道
        cf.channel().closeFuture().sync();//等待关闭
        cf2.channel().closeFuture().sync();//等待关闭
        System.out.println("Server--关闭通道！！！");
        //关闭线程组
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
        System.out.println("Server--关闭线程组！！！");
    }
}
